<script setup>
  import { ref, toRaw, watch, computed } from 'vue'
  import { SettingOutlined ,PlusCircleOutlined,CloseCircleOutlined ,ExclamationCircleOutlined} from "@ant-design/icons-vue";
  import addArticlePublish from "./addArticlePublish.vue"
  import request from "../../common/utils/request"
  import _ from 'lodash'
  import { components as formComponents } from './forms'
  import {  message } from "ant-design-vue";
  import utils from "@/common/utils/utils";

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    parentDom: {
      type: Object,
      default: null,
    },
    title: {
      type:String,
      default:''
    },
    content: {
      type:String,
      default:''
    }
  })

  const emit  = defineEmits(['onClose'])
  const accountVisible = ref(false)
  const memory_tab_accounts_obj = ref([])
  const active_memory_tab = ref()
  const chooseAccounts = ref([])
  const activeAccountId = ref()
  const group_account_List = ref([])
  const activeAccount = ref()
  const formRefs = new Map()

  const setFormRef = (formId) => {
    return (el) => {
      formRefs.set(formId, el)
    }
  }

  const memoryTabChange = (key) => {
    active_memory_tab.value = key
  }

  const delAllChooseAccount = (key) => {
    memory_tab_accounts_obj.value = memory_tab_accounts_obj.value.filter(tab => tab.key != key)
    chooseAccounts.value = chooseAccounts.value.filter(account => account.source != key)

    if(memory_tab_accounts_obj.value.length<=0){
      active_memory_tab.value = null
      activeAccountId.value  = null
    }else{
      active_memory_tab.value = _.first(memory_tab_accounts_obj.value).key
    }
  }

  const delChooseAccount = (id) => {
    chooseAccounts.value = chooseAccounts.value.filter(account => account.id != id)
 
    if( chooseAccounts.value.length <= 0){
      activeAccountId.value  = null
    } else if(activeGroupAccounts.value.length > 0) {
      activeAccountId.value = _.first(activeGroupAccounts.value).id
    } else {
      let groups = memory_tab_accounts_obj.value.map(tab => chooseAccounts.value.filter(account => account.source == tab.key)).filter(accounts => accounts.length > 0)
      let account = _.first(_.first(groups))

      active_memory_tab.value = account.source
      activeAccountId.value = account.id
    }
  }

  const chooseAccont = () => {
    accountVisible.value = true
  }

  const clearParams = ()=>{
    memory_tab_accounts_obj.value = []
    active_memory_tab.value = null
    chooseAccounts.value = []
    activeAccountId.value  = null
    group_account_List.value = []
  }

  const validateForms = () => {
    return new Promise(async (resolve, reject) => {
      let errorAccount
      
      for(let id of formRefs.keys()){
        const formRef = formRefs.get(id)
        
        try {
          await formRef.validate()
        } catch(error) {
          errorAccount = _.find(chooseAccounts.value, { id })
          console.log(errorAccount,'errorAccount');
        }

        if(errorAccount){
          reject(errorAccount)
          break;
        }
      }

      if(! errorAccount){
        resolve(errorAccount)
      }
    })
  }

  const submit = async () => {
    if(chooseAccounts.value.length==0){
      return message.warn('请选择账号')
    }
  
    try {
      await validateForms()
    } catch (account) {
      active_memory_tab.value = account.source
      activeAccountId.value = account.id
      
      message.warn(`${account.source_txt}有规则未配置，请检查`)
      return
    }

    let account = chooseAccounts.value.map(item=>{
      return {
        account_id: item.id,
        data: item.formData,
      }
    })

    let params = {
      title: props.title,
      desc: props.content,
      account,
    }
      
    request
      .post("/work_ai", "/org/platform/account/article/add", params)
      .then((res) => {
          message.success("操作成功")
          // emit("onClose", res.chat_id);
          emit("onClose");
          clearParams()
      });
  }

  const onClose = () => {
    emit('onClose')
  }

  const createAccountFormData = (source) => {
    return _.cloneDeep(_.find(formComponents, { name: source }).formData)
  }

  const activeGroupAccounts = computed(() => {
    return chooseAccounts.value.filter(account => account.source == active_memory_tab.value)
  })

  const onAccountSelected = (accounts) => {
    chooseAccounts.value = chooseAccounts.value.filter(account => _.find(accounts, { id: account.id }))

    let addAccounts = accounts
      .filter(account => !_.find(chooseAccounts.value, { id: account.id }))
      .map(account => ({ ...account, formData: createAccountFormData( account.source ), component: _.find(formComponents, { name: account.source }).component }))
    
    chooseAccounts.value = chooseAccounts.value.concat(addAccounts)
    
    const selectedGroups = chooseAccounts.value.map(account => account.source).reduce((sources, source) => {
      if(! sources.includes(source)) sources.push(source)
      return sources
    }, [])
      .filter(group => ! _.find(memory_tab_accounts_obj.value, { key: group }))
      .map(group => toRaw(_.find(group_account_List.value, { key: group })))

    memory_tab_accounts_obj.value = memory_tab_accounts_obj.value.concat(selectedGroups)

    if(! active_memory_tab.value){
      active_memory_tab.value = _.first(memory_tab_accounts_obj.value).key
    } else if(! activeAccountId.value){
      activeAccountId.value = _.first(activeGroupAccounts.value).id
    }

    accountVisible.value = false
  }
  
  watch(active_memory_tab, () => {
    activeAccountId.value = _.first(activeGroupAccounts.value)?.id??null
  })

  watch(activeAccountId, (id) => {
    activeAccount.value = id ? _.find(chooseAccounts.value, { id }) : null
  })

  watch(chooseAccounts, (newAccounts, oldAccounts) => {
    oldAccounts
      .filter(account => !_.find(newAccounts, { id: account.id }))
      .forEach(account => {
        formRefs.delete(account.id)
      })
  })

  const getAccountList = async () => {
    const { result } = await request.get("/work_ai", "/org/platform/account/group/list", {})
    group_account_List.value = result
  }

  watch(()=>props.visible,(visible)=>{
    visible &&  getAccountList()
  })
</script>

<template>
    <a-drawer
      title="发布设置"
      :visible="visible"
      :width="600"
      @close="onClose"
      :keyboard="false"
      :maskClosable="false"
      :get-container="() => parentDom"
      :wrap-style="{ position: 'absolute',right:0 }"
      :body-style="{ padding: '0', height: 'calc( 100% - 55px )' }"
    >
      <div class="list-wrap">
        <div class="left-area">
          <div class="left-header">
            <SettingOutlined class="mb-5 text-20" />
            <span>选择记忆项</span>
          </div>
          <div class="left-list">
            <div class="left-item"
              v-for="(item) of memory_tab_accounts_obj"
              :key="item.key"
              :class="{active_memory_tab: active_memory_tab == item.key}"
              @click="memoryTabChange(item.key)"
            >
              <a-tooltip>
                <img :src="item.image" class="left-item-img">
                <template #title>
                  {{ item.value }}
                </template>
              </a-tooltip>
              <CloseCircleOutlined class="choose-item-close" @click.stop="delAllChooseAccount(item.key)" />
            </div>
          </div>
        </div>
        <div class="right-area beauty-scroller-bar">
            <a-form layout="vertical" >
              <a-form-item label="账号" class="position: sticky;top: 0px;background: #ffffff;z-index: 2;padding-bottom: 24px; border-bottom: 1px solid #f1efef;" required>
                <div class="choose-list">
                  <div class="choose-item" v-for="item in activeGroupAccounts" :key="item.id">
                    <CloseCircleOutlined class="choose-item-close" @click="delChooseAccount(item.id)" />
                    <div class="account-avatar-wrapper" @click="()=>activeAccountId = item.id " :class="{ 'active-account': activeAccount.id == item.id }">
                      <a-tooltip>
                        <template #title>{{ item.nickname }}</template>
                        <img :src="item.avatar" class="account-avatar">
                      </a-tooltip>
                     
                    </div>
                    <div v-if="item.status==0" class="login-error">{{ item.status_txt }}</div>
                  </div>
                  <PlusCircleOutlined class="add-btn" @click="chooseAccont" />
                </div>
              
              </a-form-item>
          </a-form>
          <component
            v-for="account in chooseAccounts"
            :key="account.id"
            :is="account.component"
            :ref="setFormRef(account.id)"
            v-show="account.id == activeAccountId"
            v-model:formData="account.formData"
            :accountId="account.id"
            :title="title"
            :content="content"
            :group_account_list="group_account_List"
          ></component>
          <div class="text-gray-6 flex justify-center" v-if="chooseAccounts.length==0">您还没有账号，请点击上方添加按钮添加账号</div>
        </div>
      </div>
      <div class="footer">
        <a-button  @click="onClose">取消</a-button>
        <a-button type="primary" class="mx-10" @click="submit">确定</a-button>
      </div>

      <Suspense>
        <addArticlePublish
          :visible="accountVisible"
          @handleOk="onAccountSelected"
          @onClose="()=>{ accountVisible = false }"
          :group_id="active_memory_tab"
          :account="chooseAccounts">
        </addArticlePublish>
      </Suspense>
    </a-drawer>
  </template>
  <style lang="less" scoped>
  .list-wrap{
    height: calc(100% - 55px);
    display: flex;
    width: 100%;
   
  }
    .footer{
        display: flex;
        justify-content: flex-end;
        width: 100%;
        align-items: center;
        border-top: 1px solid #e5e5e5;
        height: 55px;
        background-color: #fff;
    }
    .left-area{
        width: 120px;
        border-right: 1px solid #eee;
        padding: 20px 0;
    }
    .right-area{
        flex: 1;
        padding: 20px;
        height: 100%;
        overflow-y: auto;
    }
    .left-header{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      color: var(--ss-primary-color);
      
    }
    .text-20{
        font-size: 20px;
    }
    .add-btn{
      font-size: 32px;
      cursor: pointer;
      color: var(--ss-primary-color);
      margin-left: 10px;
      margin-top: 5px;
      margin-bottom: 5px;
    }
    .accout-item{
      display: flex;
      align-items: center;
      height: 60px;
      border-bottom: 1px solid #eee;
      
    }
    .account-lable-item{
      cursor: pointer;
    }
    .account-avatar{
      width: 24px;
      height: 24px;
      border-radius: 50%;
      overflow: hidden;
      margin: 0 5px;
      object-fit: contain;
    }
    .choose-list{
      display: flex;
      flex-wrap: wrap;
    
    }
    .choose-item{
      position: relative;
      display: flex;
      flex-direction: column;
     
      align-items: center;
      margin: 5px;
      cursor: pointer;
    }
    .choose-item:hover .choose-item-close{
      visibility: visible!important;
    }
    .login-error{
      
      font-size: 12px;
      margin-top: 5px;
      background-color: red;
      border-radius: 5px;
      padding: 0px 8px;
      color: #fff;
      font-size: 12px;
    }
    .account-avatar-wrapper{
      display: flex;
      justify-content: center;
      align-items: center;
      width: 36px;
      height: 36px;
      border: 1px solid #e5e5e5;
      border-radius: 50%;
    }
    .choose-item-close{
      position: absolute;
      right: -10px;
      top: -10px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      visibility: hidden;
    }
    .left-list{

    }
    .left-item{
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 15px 0;
      padding: 10px 0;
      
      cursor: pointer;
      .choose-item-close{
      position: absolute;
      right: 15px;
      top: 0px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      visibility: hidden;
      }
     
      &:hover .choose-item-close{
        visibility: visible!important;
      }
      &:hover .choose-item-close{
        visibility: visible!important;
      }
    }
    .active_memory_tab:hover .choose-item-close{
      background-color: #e7e5f3;
    }
    .active_memory_tab{
        background-color: #e7e5f3!important;
      }
    .left-item-img{
      width: 40px;
      height: 40px;
      object-fit: contain;
    }
    .account-list{
      height: 450px;
      width: calc(100% - 200px);
      width: 100%;
      overflow-y: auto;
      margin-left: 20px;
    }
    .account-list-empty{
      width: 100%;
      height: 450px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .list-wrapper{
      display: flex;

      height: 450px;
    }
    .list-left{
      flex-shrink: 0;
      width: 199px;
      border-right: 1px solid #e5e5e5;
    }
    .tab-item{
      display: flex;
      justify-content: start;
      align-items: center;
      height: 45px;
   
      cursor: pointer;
      font-size: 14px;
      color: #333;
      font-weight: 500;
      padding: 0 10px;
      height: 50px;
    }
    .tab-active{
      background-color: #e7e5f3;
    }
    .tab-img{
      width: 30px;
      height: 30px;
      border-radius: 50%;
      object-fit: contain;
      margin-right: 10px;
    }
    .active-account{
      border:2px solid @primary-color;
    }
    .publish-tip{
      margin-top: 80px;
      
      border-radius: 5px;
      
    }
  </style>
  